<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\CoUserMoney;
use App\Models\CoUser;
use App\Models\CoUserBalanceLog;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yansongda\LaravelPay\Facades\Pay;

class CoUserMoneyController extends AdminController
{
    protected $title ='提现管理';
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new CoUserMoney(), function (Grid $grid) {
            $grid->id->sortable();
            $grid->user_id->display(function ($id){
                return CoUser::where('id',$id)->value('truename');
            });
            $grid->column('money');
            $grid->status->display(function ($status){
                if($status ==0){
                    return '待审核';
                }elseif ($status ==1){
                    return '打款中';
                }elseif ($status ==2){
                    return '提现成功';
                }else{
                    return '提现失败';
                }
            });
            $grid->column('created_at','申请时间');
//            $grid->updated_at->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
            $grid->disableCreateButton();
            $grid->disableDeleteButton();
            $grid->disableEditButton();
            $grid->disableViewButton();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
//                // 当前行的数据数组
//                $rowArray = $actions->row->toArray();

//                // 当前行的某个字段的数据
//                $id = $actions->row->id;

                // 获取当前行主键值
                $id = $actions->getKey();
                $actions->append('<a style="cursor: pointer" class="grid-row-action-5f7137974df5f" href="/admin/coUserMoney/'.$id.'/edit"><i class="feather icon-edit-1"></i> 审核</a>');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new CoUserMoney(), function (Show $show) {
            $show->id;
            $show->user_id;
            $show->money;
            $show->status;
            $show->shen_time;
            $show->created_at;
            $show->updated_at;
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CoUserMoney(), function (Form $form) {
            $form->hidden('id');
            $form->display('user_id','配送员姓名')->with(function ($user_id) {
                return CoUser::where('id',$user_id)->value('truename');
            });;
            $form->display('money');
            if($form->model()->get('status')>0){
                $form->display('status')->with(function ($status) {
                    switch ($status){
                        case 1:
                            return "审核通过";
                        case 2:
                            return "已打款";
                        default:
                            return "提现失败";
                    }
                });
                $form->disableSubmitButton();
            }else{
                $form->radio('status')->options(['1'=>'通过','3'=>'不通过'])->default(1)->required();
            }
            $form->display('created_at');
            $form->disableDeleteButton();
            $form->disableViewButton();
            $form->disableResetButton();
            $form->action('pay_order');
            //操作完成后
//            $form->saving(function (Form $form) {
//                //支付操作
//                if($form->model()->get('status') ==1){
//                    $order_no = $form->model()->get('order_no');
//                    $order = \App\Models\CoUserMoney::where('co_user_money.order_no',$order_no)->first();
//                    if($order){
//                        if($order->status ==1){
//                            return $form->error($order->status);
//                            DB::beginTransaction();
//                            //查询用户信息
//                            $user = CoUser::where('id',$order->user_id)->first();
//                            //扣账户余额
//                            $user->balance = $user->balance - $order->money;
//                            $res = $user->save();
//                            if(!$res){
//                                DB::rollBack();
//                                return $form->error('配送员余额不足');
//                                return false;
//                            }
//                            //添加记录
//                            $res = CoUserBalanceLog::add($user->id,$order->money,2,'收入提现');
//                            if(!$res){
//                                DB::rollBack();
//                                return $form->error('提现失败');
//                                return false;
//                            }
//                            //打款
//                            $order_list = [
//                                'partner_trade_no' =>$order->order_no,              //商户订单号
//                                'openid' => $user->openid,                        //收款人的openid
//                                'check_name' => 'NO_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
//                                // 're_user_name'=>$user->truename,              //check_name为 FORCE_CHECK 校验实名的时候必须提交
//                                'amount' => $order->money,                       //企业付款金额，单位为分
//                                'desc' => '帐户提现',                  //付款说明
//                            ];
//                            $wechat = Pay::wechat(config('app.wechat'));
//                            $result = $wechat->transfer($order_list);
//                            return $form->error('微信提现失败',$result);
//                            if($result['return_code'] =='SUCCESS'){
//                                DB::commit();
////                                return true;
//                            }else{
//                                return $form->error('微信提现失败');
//                            }
//                        }
//                    }
//
////                    $res = $this->pay_order($form->model()->get('order_no'));
////                    if($res == false){
////                        //失败处理
////                        $this->save_order($form->model()->get('order_no'));
////                        return $form->error('提现失败');
////                    }else{
////                        return $form->success('提现成功');
////                    }
////                }else{
////                    return $form->error('提现失败');
//                }
//            });
        });
    }

    /**
     * 提现支付
     */
    public function pay_order(Request $request){
        try {
            $id = intval($request->get('id'));
            $status = intval($request->get('status'));
            if($id<=0 || !in_array($status,[1,2])){
                return response()->json(
                    [
                        'message' => '参数错误',
                        'status' => false,
                        'redirect'=>admin_url('coUserMoney'),
                    ]
                );
            }
            $order = \App\Models\CoUserMoney::where('id',$id)->first();
            if($order){
                if($status == 1){
                    if($order->status < 1){
                        DB::beginTransaction();
                        //查询用户信息
                        $user = CoUser::where('id',$order->user_id)->first();
                        if($user->balance < $order->money){
                            return response()->json(
                                [
                                    'message' => '用户余额不足',
                                    'status' => false,
                                    'redirect'=>admin_url('coUserMoney'),
                                ]
                            );
                        }
                        //扣账户余额
                        $user->balance = $user->balance - $order->money;
                        $res = $user->save();
                        if(!$res){
                            DB::rollBack();
                            return response()->json(
                                [
                                    'message' => '扣款失败',
                                    'status' => false,
                                    'redirect'=>admin_url('coUserMoney'),
                                ]
                            );
                        }
                        //添加记录
                        $res = CoUserBalanceLog::add($user->id,$order->money,2,'收入提现');
                        if(!$res){
                            DB::rollBack();
                            return response()->json(
                                [
                                    'message' => '提现失败',
                                    'status' => false,
                                    'redirect'=>admin_url('coUserMoney'),
                                ]
                            );
                        }
                        $order->status ==2;
                        $order->shen_time = date("Y-m-d h:i:s");
                        $res = $order->save();
                        if(!$res){
                            DB::rollBack();
                            return response()->json(
                                [
                                    'message' => '提现失败',
                                    'status' => false,
                                    'redirect'=>admin_url('coUserMoney'),
                                ]
                            );
                        }
                        //打款
                        $order_list = [
                            'partner_trade_no' =>$order->order_no,              //商户订单号
                            'openid' => $user->openid,                        //收款人的openid
                            'check_name' => 'NO_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
                            // 're_user_name'=>$user->truename,              //check_name为 FORCE_CHECK 校验实名的时候必须提交
                            'amount' => $order->money*100,                       //企业付款金额，单位为分
                            'desc' => '帐户提现',                  //付款说明
                        ];
                        $wechat = Pay::wechat(config('app.wechat'));
                        $result = $wechat->transfer($order_list);
                        if($result['return_code'] =='SUCCESS'){
                            DB::commit();
                            return response()->json(
                                [
                                    'message' => '提现成功',
                                    'status' => true,
                                    'redirect'=>admin_url('coUserMoney'),
                                    'data'=>$result,
                                ]
                            );
                        }
                        DB::rollBack();
                        return response()->json(
                            [
                                'message' => '提现失败',
                                'status' => false,
                                'redirect'=>admin_url('coUserMoney'),
                                'data'=>$result,
                            ]
                        );
                    }
                    return response()->json(
                        [
                            'message' => '审核失败',
                            'status' => false,
                            'redirect'=>admin_url('coUserMoney'),
                        ]
                    );
                }else{
                    $order->status ==3;
                    $order->shen_time = date("Y-m-d h:i:s");
                    $res = $order->save();
                    if($res){
                        return response()->json(
                            [
                                'message' => '操作成功',
                                'status' => true,
                                'redirect'=>admin_url('coUserMoney'),
                            ]
                        );
                    }
                    return response()->json(
                        [
                            'message' => '操作失败',
                            'status' => false,
                            'redirect'=>admin_url('coUserMoney'),
                        ]
                    );
                }

            }
        } catch (\Exception $e) {
            return response()->json(
                [
                    'message' => '提现失败',
                    'status' => false,
                    'redirect'=>admin_url('coUserMoney'),
                    'data'=>$e,
                ]
            );
        }
    }


    protected function rount_data($message,$status=false){
        return response()->json(
            [
                'message' => '测试',
                'status' => false,
                'redirect'=>admin_url('coUserMoney'),
            ]
        );
    }
    /**
     * 提现失败操作
     * @param $order_no
     */
    protected function save_order($order_no){
        $order = \App\Models\CoUserMoney::where('co_user_money.order_no',$order_no)->first();
        if($order){
            $order->status = 3;
            $order->remarks = '提现失败';
            return $order->save();
        }
        return false;
    }
}
